#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#include "shunxudui.h"

pthread_mutex_t lock;
pthread_cond_t empety;
pthread_cond_t new;
sequeue_t *queue;

void* getover(void* arg){

    for(int i =0;i< 20;i++){
        // sleep(1);
        pthread_mutex_lock(&lock);
        if(IsEmptySequeue(queue) == 1){
            pthread_cond_wait(&new,&lock);//等待新数据
        }
        printf("%d \n",OutSequeue(queue));

        pthread_cond_signal(&empety);//发送信号“有空位”
                
        pthread_mutex_unlock(&lock);

    }
    // printf("\n");


}


int main(void){

    pthread_t tid=-1;

    if(pthread_cond_init(&new,NULL) == -1){
        return -1;
    }
    if(pthread_cond_init(&empety,NULL) == -1){
        return -1;
    }

    
    

    queue = CreateEmptySequeue();
    if(queue == NULL){
        printf("sxlb create err\n");
        queue ==NULL;
        return -1;
    }

    if(pthread_mutex_init(&lock,NULL) != 0){
        perror("pthread_mutex_init err");
        free(queue);
        queue=NULL;
        return -1;
    }
    
    if(pthread_create(&tid,NULL,getover,NULL) != 0){
        perror("swap_create err");
        free(queue);
        queue=NULL;
        return -1;
    }



   for(int i =0;i< 20;i++){

        // sleep(1);
        pthread_mutex_lock(&lock);
        if(IsFullSequeue(queue) == 1){
            pthread_cond_wait(&empety,&lock);//等待空位
        }
        InSequeue(queue, i);

        pthread_cond_signal(&new);//发送信号“有新数据”

        pthread_mutex_unlock(&lock);


    }

    



    if(pthread_join(tid,NULL)){
        printf("error\n");
    }
    free(queue);
    queue=NULL;


    return 0;
}